ajax('/admin/category/list', function (data) {
    document.querySelector('.table tbody').innerHTML = template('template', data)
    document.querySelectorAll('.btn-info').forEach(function (button) {
        button.addEventListener('click', function () {
            $('#editModal').modal('show')
            document.querySelector('#editModal #name').value = this.parentElement.previousElementSibling.previousElementSibling.innerHTML
            document.querySelector('#editModal #slug').value = this.parentElement.previousElementSibling.innerHTML
            document.querySelector('#editModal .btn-primary').onclick = () => {
                console.log(this.dataset.id)
                let name = document.querySelector('#editModal #name').value.trim()
                let slug = document.querySelector('#editModal #slug').value.trim()
                ajax('/admin/category/edit', undefined, 'post', `id=${this.dataset.id}&name=${name}&slug=${slug}`)
                ajax('/admin/category/list', function (data) {
                    document.querySelector('.table tbody').innerHTML = template('template', data)
                })
            }
        })
    })
    document.querySelectorAll('.btn-danger').forEach(function (button) {
        button.addEventListener('click', function () {
            if (confirm('确定要删除吗！')) {
                ajax('/admin/category/delete', undefined, 'post', `id=${this.previousElementSibling.dataset.id}`)
                ajax('/admin/category/list', function (data) {
                    document.querySelector('.table tbody').innerHTML = template('template', data)
                })
            }
        })
    })
})
document.querySelector('#editModal .btn-default').onclick = function () {
    document.querySelector('#editModal #name').value = ''
    document.querySelector('#editModal #slug').value = ''
}

document.querySelector('#myModal .btn-default').onclick = function () {
    document.querySelector('#myModal #name').value = ''
    document.querySelector('#myModal #slug').value = ''
}
document.querySelector('#myModal .btn-primary').onclick = function () {
    let name = document.querySelector('#myModal #name').value.trim()
    let slug = document.querySelector('#myModal #slug').value.trim()
    ajax('/admin/category/add', function (data) {
        console.log(data.msg)
        ajax('/admin/category/list', function (data) {
            document.querySelector('.table tbody').innerHTML = template('template', data)
        })
    }, 'post', `name=${name}&slug=${slug}`)

    $('#myModal').modal('hide')
    document.querySelector('#myModal #name').value = ''
    document.querySelector('#myModal #slug').value = ''
}